package com.gjy.redis.controller;

import com.gjy.redis.annotation.RedisLock;
import com.gjy.redis.annotation.RedisLockAnnotation;
import com.gjy.redis.domain.AjaxResult;
import com.gjy.redis.domain.RedisLockPrefix;
import com.gjy.redis.domain.RedisLockTypeEnum;
import com.gjy.redis.util.JedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-26 21:41:22
 */
@RestController
@RequestMapping("/lock")
public class LockController {

    private static final Logger log = LoggerFactory.getLogger(LockController.class);
    @Resource
    private Jedis jedis;

    @PostMapping("/jedis")
    public AjaxResult jedisLockScript(@RequestBody Map<String, String> request) {
        try {
            String key = request.get("key");
            String value = request.get("value");
            String timeout = request.get("timeout");
            String type = request.get("type");

            if (type.equals("lock")) {
                boolean lock = JedisUtil.build(jedis).lock(key, value, timeout);
                return AjaxResult.builder().message("lock").code(200).data(lock).build();
            } else if (type.equals("unlock")) {
                boolean unlock = JedisUtil.build(jedis).unlock(key, value);
                return AjaxResult.builder().message("lock").code(200).data(unlock).build();
            } else {
                return AjaxResult.builder().message("unknown").code(-100).build();
            }
        } catch (Exception e) {
            log.error("has some error", e);
        }
        return AjaxResult.builder().message("OK").code(200).build();
    }

    @GetMapping("/t2")
    @RedisLock(prefix = RedisLockPrefix.BUSINESS, timeout = 60, msg = "测试加锁执行中", args = "#userId", value = "#value")
    public AjaxResult testRedisLock2(@RequestParam("userId") Long userId, @RequestParam("value") String value) {
        try {
            log.info("userId: {},{}", userId, value);
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            log.error("has some error", e);
        }
        return AjaxResult.builder().message("OK").code(200).build();
    }

    @GetMapping("/testRedisLock")
    @RedisLockAnnotation(typeEnum = RedisLockTypeEnum.ONE, lockTime = 3)
    public String testRedisLock(@RequestParam("userId") Long userId) {
        try {
            log.info("睡眠执行前");
            Thread.sleep(10000);
            log.info("睡眠执行后");
            log.info("userId: {}", userId);
        } catch (Exception e) {
            log.error("has some error", e);
        }
        return null;
    }

}
